﻿#include "udpform.h"
#include "ui_udpform.h"

UdpForm::UdpForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UdpForm)
{
    ui->setupUi(this);

    ui->m_serverUrl->setText("127.0.0.1:9002");
    ui->m_clientUrl->setText("127.0.0.1:9002");

    ui->m_recvText->setReadOnly(true);

    ui->m_btnStop->setEnabled(false);

    connect(ui->m_btnListen, SIGNAL(clicked()), this, SLOT(on_listen()));
    connect(ui->m_btnStop, SIGNAL(clicked()), this, SLOT(on_stop()));
    connect(ui->m_btnClear, SIGNAL(clicked()), this, SLOT(on_clear()));
    connect(ui->m_btnSend, SIGNAL(clicked()), this, SLOT(on_send()));
}

UdpForm::~UdpForm()
{
    delete ui;
}

void UdpForm::on_listen()
{
    QUrl qUrl = QUrl::fromUserInput(ui->m_serverUrl->text());
    if(!qUrl.isValid())
    {
        return;
    }

    uSocket = new QUdpSocket(this);

    uSocket->bind(QHostAddress(qUrl.host()), static_cast<quint16>(qUrl.port()));
    connect(uSocket, SIGNAL(readyRead()), this, SLOT(on_receive()));

    ui->m_btnListen->setEnabled(false);
    ui->m_btnStop->setEnabled(true);

    emit statusBarShow(QString::fromLocal8Bit("Udp监听成功"));
}

void UdpForm::on_receive()
{
    QByteArray ba;
    while(uSocket->hasPendingDatagrams())
    {
        ba.resize(static_cast<int>(uSocket->pendingDatagramSize()));
        uSocket->readDatagram(ba.data(), ba.size());
        ui->m_recvText->appendPlainText(QString(ba));
    }

    emit statusBarShow(QString::fromLocal8Bit("Udp接收完成"));
}

void UdpForm::on_stop()
{
    uSocket->close();

    ui->m_btnListen->setEnabled(true);
    ui->m_btnStop->setEnabled(false);

    emit statusBarShow(QString::fromLocal8Bit("Udp停止监听"));
}

void UdpForm::on_clear()
{
    ui->m_recvText->clear();

    emit statusBarShow(QString::fromLocal8Bit("Udp清空内容"));
}

void UdpForm::on_send()
{
    QUdpSocket qus;
    QUrl qUrl = QUrl::fromUserInput(ui->m_clientUrl->text());
    if(!qUrl.isValid())
    {
        return;
    }
    qus.writeDatagram(ui->m_sendText->toPlainText().toUtf8(), QHostAddress(qUrl.host()), static_cast<quint16>(qUrl.port()));

    emit statusBarShow(QString::fromLocal8Bit("Udp发送成功"));
}
